package com.mattmckay.server;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

/**
* <p>Title:ProccessPDF</p>
* <p>Description: This class allows us to process our pdf files.
* Such as modifying, and converting our pdf into PNG files </p>
* @author Matt, Tom, Andrew, Kong
* @email matt.mckay@my.uwrf.edu,tom.florin@my.uwrf.edu,
* andrew.kathan@my.uwrf.edu,kong.xiong-1@my.uwrf.edu
* @date December 1st,2011*/

public class ProcessPDF {

	/**
	 * Constructor
	 */
	public ProcessPDF() {

	}

	/**
	 * Used to convert the current PDF into a PNG
	 */
	public static byte[] ConvertPDFtoPNG(InputStream userstream)throws Exception {
		System.out.println("ProcessPDF.ConvertPDFtoPNG: PDF Bytes Have Been read");
		RandomAccessFile raf = new RandomAccessFile(InputStreamtoFile(userstream), "r");
		FileChannel fc = raf.getChannel();
		ByteBuffer buf = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		PDFFile pdfFile = new PDFFile(buf);
		System.out.println("ProcessPDF.ConvertPDFtoPNG: pdffile created from inputstream");
		Image image;
		PDFPage page = pdfFile.getPage(1);
		Rectangle2D r2d = page.getBBox();
		image = page.getImage((int) r2d.getWidth(), (int) r2d.getHeight(), r2d,null, true, true);
		BufferedImage bufferedimage = toBufferedImage(image);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(bufferedimage, "png", baos);
		baos.flush();
		raf.close();
		image.flush();
		return baos.toByteArray();
	}

	/**
	 * toBufferedImage(Image image) Used to create buffered images out of
	 * precondition: none postcondition: none
	 */
	private static BufferedImage toBufferedImage(Image image) {
		if (image instanceof BufferedImage) {
			return (BufferedImage) image;
		}
		// This code ensures that all the pixels in the image are loaded
		image = new ImageIcon(image).getImage();
		// Determine if the image has transparent pixels; for this method's
		// implementation, see e661 Determining If an Image Has Transparent
		// Pixels
		boolean hasAlpha = hasAlpha(image);
		// Create a buffered image with a format that's compatible with the
		// screen
		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		try {
			// Determine the type of transparency of the new buffered image
			int transparency = Transparency.OPAQUE;
			if (hasAlpha) {
				transparency = Transparency.BITMASK;
			}
			// Create the buffered image
			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(image.getWidth(null),
					image.getHeight(null), transparency);
		} catch (HeadlessException e) {
			// The system does not have a screen
		}
		if (bimage == null) {
			// Create a buffered image using the default color model
			int type = BufferedImage.TYPE_INT_RGB;
			if (hasAlpha) {
				type = BufferedImage.TYPE_INT_ARGB;
			}
			bimage = new BufferedImage(image.getWidth(null),
					image.getHeight(null), type);
		}
		// Copy image to buffered image
		Graphics g = bimage.createGraphics();
		// Paint the image onto the buffered image
		g.drawImage(image, 0, 0, null);
		g.dispose();
		return bimage;
	}
	/**
	 * Checks to see if the image is tranparent or not.
	 * @param image
	 * @return cm.hasAlpha()
	 */
	private static boolean hasAlpha(Image image) {
		// If buffered image, the color model is readily available
		if (image instanceof BufferedImage) {
			BufferedImage bimage = (BufferedImage) image;
			return bimage.getColorModel().hasAlpha();
		}
		// Use a pixel grabber to retrieve the image's color model;
		// grabbing a single pixel is usually sufficient
		PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
		try {
			pg.grabPixels();
		} catch (InterruptedException e) {
		}
		// Get the image's color model
		ColorModel cm = pg.getColorModel();
		return cm.hasAlpha();
	}
	
	/**
	 * InputStreamtoFile method allows the server to upload
	 * the image onto a users.
	 * @param stream
	 * @return
	 * @throws Exception
	 */
	private static File InputStreamtoFile(InputStream stream) throws Exception {
		File f;
		try {
			f = new File("outFile.pdf");
			OutputStream out = new FileOutputStream(f);
			byte buf[] = new byte[1024];
			int len;
			while ((len = stream.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.close();
		} catch (Exception ex) {
			throw ex;
		}

		return f;
	}

}
